#Temporay remove

# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution	
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
import netsvc
from osv import fields, osv
import ir

from tools.misc import currency
from tools.translate import _

import mx.DateTime
from mx.DateTime import RelativeDateTime, now, DateTime, localtime

class kdvn_purchase_currency(osv.osv):
    _name = "kdvn.purchase.currency"
    _description = "KDVN Purchase Currency"
    
    def _current_rate(self, cr, uid, ids, name, arg, context={}):
        res={}
        if context:
            if 'date' in context:
                date=context['date']
            else:
                date=time.strftime('%Y-%m-%d')
            date= date or time.strftime('%Y-%m-%d')
            for id in ids:
                cr.execute("SELECT kdvn_purchase_currency_id, rate FROM kdvn_purchase_currency_rate WHERE kdvn_purchase_currency_id = %s AND name <='%s' ORDER BY name desc LIMIT 1" %(id, date))
                if cr.rowcount:
                    id, rate=cr.fetchall()[0]
                    res[id]=rate
                else:
                    res[id]=0
        return res

    def compute(self, cr, uid, from_currency_id, to_currency_id, from_amount, round=False, context={}):
        if not from_currency_id:
            from_currency_id = to_currency_id
        if not to_currency_id:
            to_currency_id = from_currency_id
#        xc = self.browse(cr, uid, [from_currency_id,to_currency_id], context=context)
#        from_currency = (xc[0].id == from_currency_id and xc[0]) or xc[1]
#        to_currency = (xc[0].id == to_currency_id and xc[0]) or xc[1]
        date = context.get('date', time.strftime('%Y-%m-%d'))
        #raise osv.except_osv("E",from_currency.rate)
        cr.execute("Select fnpo_compute(%s,%s,'%s'::date)" % (to_currency_id,from_currency_id,date))
        #if from_currency['rate'] == 0 or to_currency['rate'] == 0:
#        if from_currency.rate == 0 or to_currency.rate == 0:
#            date = context.get('date', time.strftime('%Y-%m-%d'))
#            if from_currency['rate'] == 0:
#                code = from_currency.code
#            else:
#                code = to_currency.code
#            raise osv.except_osv(_('Error'), _('No rate found \n' \
#                    'for the currency: %s \n' \
#                    'at the date: %s') % (code, date))
        rate_obj = cr.fetchone()
        if rate_obj:
            rate = rate_obj[0]
        else:
            rate = 0.0
        
        if to_currency_id==from_currency_id:
            return from_amount
        else:
            return (from_amount * rate)


    _columns = {
        'name': fields.char('Currency', size=32, required=True),
        'rate': fields.function(_current_rate, method=True, string='Current Rate', digits=(12,6),
            help='The rate of the currency to the currency of rate 1'),
        'kdvn_rate_ids': fields.one2many('kdvn.purchase.currency.rate', 'kdvn_purchase_currency_id', 'Rates')
    }
    _sql_constraints = [('name_purchase_currerncy_unique', 'unique (name)', 'KDVN Error: The name of the purchase currency must be unique !')]
    
    def _onchange_name(self, cr, uid, ids, name=False):
        invoice_addr_id = False
        address_id = False
        if name:
            name=name.upper()
        result = {'value': {'name': name}}
        return result 
    
    def name_search(self, cr, uid, name, args=[], operator='ilike', context={}, limit=80):
        args2 = args[:]
        ids = []
        if name:
            args_n = [('name','=', name.upper())]
            ids = self.search(cr, uid, args+args_n, limit=limit)
            if not ids:
                args_n= [('name',operator, name)]
                ids = self.search(cr, uid, args+args_n, limit=limit)
        else:
            ids = self.search(cr, uid, args, limit=limit)
        res = self.name_get(cr, uid, ids, context)
        return res
    def init(self, cr):               
                
                cr.execute("CREATE OR REPLACE FUNCTION fnpo_compute(fromcurr integer, tocurr integer, datecurr date)\
                                RETURNS numeric AS\
                                $BODY$\
                                Select  case when $1=$2 then 1 else (Select rate/(Select rate from kdvn_purchase_currency_rate where kdvn_purchase_currency_id=$1 and name=(Select max(name) as name\
                                from kdvn_purchase_currency_rate where kdvn_purchase_currency_id=$1 and name<=$3)) from kdvn_purchase_currency_rate where ($1=$2) or (kdvn_purchase_currency_id=$2 and name=(Select max(name) as name\
                                from kdvn_purchase_currency_rate where kdvn_purchase_currency_id=$2 and name<=$3))) end;\
                                $BODY$\
                                LANGUAGE 'sql' VOLATILE\
                                COST 100;")
                cr.execute("CREATE OR REPLACE FUNCTION fnpo_compute(fromcurr integer, tocurr integer, datecurr timestamp without time zone)\
                                RETURNS numeric AS\
                                $BODY$\
                                Select  case when $1=$2 then 1 else (Select rate/(Select rate from kdvn_purchase_currency_rate where kdvn_purchase_currency_id=$1 and name=(Select max(name) as name\
                                from kdvn_purchase_currency_rate where kdvn_purchase_currency_id=$1 and name<=$3)) from kdvn_purchase_currency_rate where ($1=$2) or (kdvn_purchase_currency_id=$2 and name=(Select max(name) as name\
                                from kdvn_purchase_currency_rate where kdvn_purchase_currency_id=$2 and name<=$3))) end;\
                                $BODY$\
                                LANGUAGE 'sql' VOLATILE\
                                COST 100;")

                cr.execute("CREATE OR REPLACE FUNCTION fnpo_compute(fromcurr integer, tocurr integer,datecurr timestamp)\
                                RETURNS numeric AS\
                                $BODY$\
                                Select  case when $1=$2 then 1 else (Select rate/(Select rate from kdvn_purchase_currency_rate where kdvn_purchase_currency_id=$1 and name=(Select max(name) as name\
                                from kdvn_purchase_currency_rate where kdvn_purchase_currency_id=$1 and name<=$3)) from kdvn_purchase_currency_rate where ($1=$2) or (kdvn_purchase_currency_id=$2 and name=(Select max(name) as name\
                                from kdvn_purchase_currency_rate where kdvn_purchase_currency_id=$2 and name<=$3))) end;\
                                $BODY$\
                                LANGUAGE 'sql' VOLATILE\
                                COST 100;")
                #Convert currency id to currency name
                cr.execute("CREATE OR REPLACE FUNCTION fnpo_curridtoname(currid integer) RETURNS text AS 'select name from kdvn_purchase_currency where id=$1' \
                        LANGUAGE 'sql' VOLATILE COST 100;")

                #Convert currency name to currency id
                cr.execute("CREATE OR REPLACE FUNCTION fnpo_currnametoid(pcurrname text) RETURNS integer AS \
                        'Select id from kdvn_purchase_currency where name=$1' LANGUAGE 'sql' VOLATILE COST 100;")

kdvn_purchase_currency()

class kdvn_purchase_currency_rate(osv.osv):
    _name = "kdvn.purchase.currency.rate"
    _description = "KDVN Purchase Currency Rate"
    _columns = {
        'name': fields.date('Date', required=True, select=True),
        'rate': fields.float('Rate', digits=(12,6), required=True),
        'kdvn_purchase_currency_id': fields.many2one('kdvn.purchase.currency', 'Currency', readonly=True)
    }
    _sql_constraints = [('name_purchase_currerncy_rate_unique', 'unique (name,kdvn_purchase_currency_id)', 'KDVN Error: The date of the currency must be unique !')]
    _defaults = {
        'name': lambda *a: time.strftime('%Y-%m-%d'),
        'rate':lambda *a:0.0,
    }
    _order = "name desc"
    def _onchange_rate(self, cr, uid, ids, rate=0.0):
        result = {'value': {'rate': rate}}
        return result 
kdvn_purchase_currency_rate()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

